//
//  PresentAnimator.swift
//  DCSwiftPresent&Push
//
//  Created by point on 2016/11/19.
//  Copyright © 2016年 dacai. All rights reserved.
//

import UIKit

class PresentAnimator: NSObject {
    var presntFrame:CGRect = CGRect.zero
    var isPresent = true
}

extension PresentAnimator: UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning,UINavigationControllerDelegate {
    //改变frame大小
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        let dcPresentationController =  DetailPresentationController(presentedViewController: presented, presenting: presenting)
        dcPresentationController.presntFrame = presntFrame
        return dcPresentationController
    }
    //动画时间
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.25
    }
    
    //获取弹出的View 获取消息的View
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        if(isPresent){
            animateForPresent(transitionContext: transitionContext)
        }else{
            animationForDismissedView(transitionContext: transitionContext)
        }
    }
    
    
    
    
    //自定义弹出动画
    func animateForPresent(transitionContext: UIViewControllerContextTransitioning) {
        let presentView = transitionContext.view(forKey: .to)
        
        transitionContext.containerView.addSubview(presentView!)
        presentView?.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
        presentView?.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
            presentView?.transform = CGAffineTransform.identity
        }) { (_) in
            transitionContext.completeTransition(true)
        }
    }
    
    // 自定义消失动画
    private func animationForDismissedView(transitionContext: UIViewControllerContextTransitioning) {
        
        let dismissView = transitionContext.view(forKey: .from)
        UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in
            dismissView?.transform = CGAffineTransform(scaleX: 0.00001, y: 0.00001)
        }) { (_) -> Void in
            dismissView?.removeFromSuperview()
            transitionContext.completeTransition(true)
        }
    }
    
    //改变弹出动画
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = true
        return self
    }
    
    //改变消失动画
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = false
        return self
    }
    
    
    
}
